<template>
    <div class="render__container" >
        <iframe :src="iframeSrc" frameborder="0" @load="handleIframeLoad"></iframe>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getAllFunctions } from '@/service/funcMenuService'
import { ROUTE_NAMES } from '@/constants/routes.js'
import { eventBus } from '@/service/eventService'
import { setBrowserTitle } from '@/service/funcMenuService'
import { SYSTEM_NAME} from '@/constants/layout.js'
const route = useRoute()
const router = useRouter()

const iframeSrc = ref('')

const navigateToError404 = () => {
    router.push({
        name: ROUTE_NAMES.PC_ERROR404,
    })
}


const initEventListeners = () => {
    eventBus.on('refreshPageEvent', () => {
        if (iframeSrc.value) {
            const currentSrc = iframeSrc.value
            iframeSrc.value = ''
            setTimeout(() => {
                iframeSrc.value = currentSrc
            }, 10)
        }
    })
}

onMounted(() => {
    initEventListeners()
})

const handleFunctionIdChange = async (fid) => {
    iframeSrc.value = ''


    try {
        const allFunctions = await getAllFunctions()
        const targetFunction = allFunctions.find((item) => item.ID === fid)

        if (targetFunction && targetFunction.NavigateUrl) {
            iframeSrc.value = targetFunction.NavigateUrl
            setBrowserTitle(`${targetFunction.Name}-${targetFunction.GroupName}-${SYSTEM_NAME}`)
        } else {
            navigateToError404()
        }
    } catch (error) {
        console.error('获取功能列表失败:', error)
        navigateToError404()
    }
}


const handleIframeLoad = () => {
    eventBus._emit('pageLoadedEvent')
}
watch(() => route.query.fid, handleFunctionIdChange, { immediate: true })
</script>

<style scoped>
.render__container {
    width: 100%;
    height: 100%;
    margin-top: 11px;
    border-radius: 12px;
}

.render__container iframe {
    width: 100%;
    height: calc(100vh - var(--layout-height));
    border-radius: 12px;
}
</style>